<?php
namespace app\server;

use think\Exception;
use think\facade\Cache;
use app\common\lib\ErrorCode;
use app\common\facade\WebSocketToken;
use app\server;
trait  websocket
{
    /** 开启 */
    public function onOpen( $server, $request){
        $request_get = $request->get;
        $token = isset($request_get['token'])?$request_get['token']:"";
        $user_id = Cache::store('redis')->get($token);
        if($user_id && $token){
            //绑定user_id & fd
            WebSocketToken::bind_fd($user_id,$request->fd);
            //发送消息
            $server->push($request->fd, json_encode(["error"=>ErrorCode::$NO_ERROR,"msg"=>"握手成功！"],JSON_UNESCAPED_UNICODE));
        }else{
            //发送消息
            $server->push($request->fd, json_encode(["error"=>ErrorCode::$SOCKET_LOGIN_ERROR,"msg"=>"未登录"],JSON_UNESCAPED_UNICODE));
            $server->disconnect($request->fd,1000,"未登录");
        }
    }
    /** 消息响应 */
    public function onMessage($server, $frame){
        try{
            $data = json_decode($frame->data,true);
            if(!isset($data['type']) || !isset($data['data'])) throw new Exception("参数错误");

            // 逻辑处理
            $service = new service($frame->fd);
            $service->run($data['type'],$data['data']);

        }catch (Exception $e ){
            //发送消息
            $server->push($frame->fd, json_encode(["error"=>ErrorCode::$USUAL_ERROR,"msg"=>$e->getMessage()]));
        }
    }
    /** 关闭 */
    public function onClose($ser, $fd){
        echo "client {$fd} closed\n";
    }
}